<template>
    <Headernav-music></Headernav-music>
    <view class="player">
		
        <!-- 唱针 -->
        <view class="needle" :class="{ 'needle-playing': isPlaying }">
            <image src="/static/iconfont/needle.png" mode="aspectFit"></image>
        </view>
        <!-- 唱盘 -->
        <view class="disc" :class="{ 'rotate': isPlaying }">
            <image src="/static/iconfont/idcs.png" mode="aspectFit"></image>
            <!-- 专辑封面 -->
            <view class="album-art">
                <image :src="song.picUrl" mode="aspectFit"></image>
            </view>
        </view>
        <!-- 歌曲信息 -->
        <view class="song-info">
            <view class="song-name">{{ song.name }}</view>
            <view class="artist-name">{{ song.artist }}</view>
        </view>
     
        <scroll-view scroll-y="true" class="lyric-scroll" :scroll-top="lyricScrollTop">
            <view class="lyric-line" 
                  v-for="(line, index) in parsedLyrics" 
                  :key="index"
                  :class="{ 'highlight': index === currentLyricIndex }"   
                  @click="jumpToLyric(line.time)">        
                {{ line.lyric }}
            </view>
        </scroll-view>
        <!-- 进度条 -->
        <view class="progress-container" @touchstart="onProgressTouchStart" @touchmove="onProgressTouchMove" @touchend="onProgressTouchEnd">
            <view class="progress-bar">
                <view class="progress" :style="{ width: progress + '%' }"></view>
            </view>
            <view class="progress-thumb" :style="{ left: progress + '%' }"></view>
        </view>
        <!-- 播放时间显示 -->
        <view class="time-display">
            <text>{{ formatTime(currentTime) }}</text>
            <text>/</text>
            <text>{{ formatTime(duration) }}</text>
        </view>
        <!-- 控制按钮 -->
        <view class="control-buttons">
            <text class="iconfont" :class="isPlaying ? 'icon-zanting' : 'icon-yinlebofangqi'" @click="getPlay"></text>
        </view>
    </view>
</template>

<script>
import { songDetail, songUrl, songLyric } from '../../common/api.js'; //歌词api

export default {
    data() {
        return {
            title: '',
            song: {
                id: '',
                name: '',
                artist: '',
                songUrl: '',
                picUrl: '',
                lyric: ''
            },
            innerAudioContext: null, // 初始化为 null
            isPlaying: false,
            progress: 0, // 进度条进度
            isDragging: false,
            lyricLines: [],
            parsedLyrics: [],
            currentLyricIndex: 0,
            currentTime: 0, // 当前播放时间
            duration: 0, // 总时长
            lyricScrollTop: 0 // 歌词滚动位置
        };
    },
    onLoad(options) {
        let songID = options.songId;
        if (!songID) {
            console.error('未获取到歌曲 ID');
            return;
        }
        this.loadSongDetail(songID);
        this.loadSongUrl(songID);
        this.loadSongLyric(songID);
    },
    methods: {
        async loadSongDetail(songID) {
            try {
                const res = await songDetail(songID);
                if (res.data && res.data.songs && res.data.songs.length > 0) {
                    this.title = res.data.songs[0].name;
                    this.song.name = this.title;
                    this.song.picUrl = res.data.songs[0].al.picUrl;
                    this.song.artist = res.data.songs[0].ar.map(artist => artist.name).join(', ');
                    console.log('专辑封面图片链接:', this.song.picUrl); // 打印图片链接
                }
            } catch (err) {
                console.error('获取歌曲详情失败:', err);
                uni.showToast({
                    title: '获取歌曲详情失败: ' + (err.message || '未知错误'),
                    icon: 'none',
                    duration: 3000
                });
            }
        },
        async loadSongUrl(songID) {
            try {
                const res = await songUrl(songID);
                if (res.data && res.data.data && res.data.data.length > 0) {
                    this.song.songUrl = res.data.data[0].url;
                    this.innerAudioContext = uni.createInnerAudioContext();
                    this.innerAudioContext.src = this.song.songUrl;
                    this.innerAudioContext.onPlay(() => {
                        this.isPlaying = true;
                    });
                    this.innerAudioContext.onPause(() => {
                        this.isPlaying = false;
                    });
                    this.innerAudioContext.onTimeUpdate(() => {
                        if (!this.isDragging) {
                            const currentTime = this.innerAudioContext.currentTime;
                            const duration = this.innerAudioContext.duration;
                            this.currentTime = currentTime;
                            this.duration = duration;
                            this.progress = (currentTime / duration) * 100;
                            this.syncLyric(currentTime);
                        }
                    });
                    console.log('innerAudioContext 初始化成功'); // 添加日志
                }
            } catch (err) {
                console.error('获取歌曲链接失败:', err);
                uni.showToast({
                    title: '获取歌曲链接失败: ' + (err.message || '未知错误'),
                    icon: 'none',
                    duration: 3000
                });
            }
        },
        async loadSongLyric(songID) {
            try {
                const res = await songLyric(songID);
                if (res.data && res.data.lrc) {
                    this.song.lyric = res.data.lrc.lyric;
                    this.lyricLines = this.song.lyric.split('\n');
                    this.parseLyrics();
                }
            } catch (err) {
                console.error('获取歌曲歌词失败:', err);
                uni.showToast({
                    title: '获取歌曲歌词失败: ' + (err.message || '未知错误'),
                    icon: 'none',
                    duration: 3000
                });
            }
        },
        getPlay() {
            if (!this.innerAudioContext) {
                console.error('音频上下文未初始化');
                uni.showToast({
                    title: '音频加载中，请稍后再试',
                    icon: 'none'
                });
                return;
            }
            if (this.isPlaying) {
                this.innerAudioContext.pause();
            } else {
                this.innerAudioContext.play();
            }
        },
        onProgressTouchStart() {
            this.isDragging = true;
        },
       onProgressTouchMove(e) {
             if (this.isDragging) {
                 const touchX = e.touches[0].clientX;
                 uni.createSelectorQuery().in(this).select('.progress-container').boundingClientRect((rect) => {
                     if (rect) {
                         let newProgress = ((touchX - rect.left) / rect.width) * 100;
                         newProgress = Math.max(0, Math.min(100, newProgress));
                         this.progress = newProgress;
                         const duration = this.innerAudioContext.duration;
                         const seekTime = (this.progress / 100) * duration;
                         if (this.innerAudioContext) {
                             this.innerAudioContext.seek(seekTime);
                             this.currentTime = seekTime;
                             this.syncLyric(seekTime); 
                         } //同步歌词到对应位置
                     }
                 }).exec();
             }
         },
        onProgressTouchEnd() {
            this.isDragging = false;
        },
		
        parseLyrics() {
			
            const regex = /\[(\d{2}):(\d{2})\.(\d{2,3})\](.*)/;//正则表达式 
            this.parsedLyrics = this.lyricLines.map(line => {
                const match = line.match(regex);
                if (match) {
                    const minutes = parseInt(match[1], 10);
                    const seconds = parseInt(match[2], 10);
                    const milliseconds = parseInt(match[3], 10);
                    const time = minutes * 60 + seconds + milliseconds / 1000;
                    const lyric = match[4];
                    return { time, lyric };
                }
                return null;
            }).filter(line => line !== null);
        },//歌词
        syncLyric(currentTime) { 
            for (let i = this.parsedLyrics.length - 1; i >= 0; i--) {
                if (this.parsedLyrics[i].time <= currentTime) {
                    if (this.currentLyricIndex!== i) {
                        this.currentLyricIndex = i; //滚动到当前歌词行
                        const query = uni.createSelectorQuery().in(this);
                        query.select(`.lyric-line:nth-child(${i + 1})`).boundingClientRect((rect) => {
                            if (rect) {
                                const scrollView = uni.createSelectorQuery().select('.lyric-scroll');
                                scrollView.boundingClientRect((scrollRect) => {
                                    if (scrollRect) {
                                        this.lyricScrollTop = rect.top - scrollRect.top + this.lyricScrollTop;
                                    }
                                }).exec();    
                            }
                        }).exec();
                    }
                    break;
                }
            }
        },
        jumpToLyric(time) {
            if (this.innerAudioContext) {
                this.innerAudioContext.seek(time);
                const duration = this.innerAudioContext.duration;
                this.progress = (time / duration) * 100; // 更新进度条
                this.currentTime = time;
                this.syncLyric(time); // 同步歌词到对应位置
            }
        },
        formatTime(time) {
            const minutes = Math.floor(time / 60);
            const seconds = Math.floor(time % 60);
            return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
    },
    onUnload() {
        if (this.innerAudioContext) {
            this.innerAudioContext.destroy();
            this.isPlaying = false;
            this.progress = 0;
            this.currentTime = 0;
            this.duration = 0;
            this.currentLyricIndex = 0;
            this.lyricScrollTop = 0;
        }
    }
};
</script>

<style>
.header-music-nav{
    background-color: gray;
}

.lyric-line {
    border: none; 
    margin-bottom: 10px;
    transition: color 0.3s ease;
}

.lyric-line:hover {
    color: #d43c33;
}

.highlight {
    color: #d43c33;
    font-weight: bold;
}


.player {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
    position: relative;
    background-color: black;
    color: #fff;
}
.needle {
    position: absolute;
    top: 10%;
    left: 50%;
    transform: translateX(-70%);
    width: 70px;
    height: auto;
    z-index: 2;
    transform-origin: top center;
    transition: transform 0.3s ease; /* 添加过渡效果 */
}

.disc {
    width: 300px;
    height: 300px;
    position: relative;
    margin-bottom: 40px; /* 增加唱盘和进度条之间的间距 */
    transition: transform 0.3s ease;
}

.disc image {
    width: 100%;
    height: 100%;
}

.album-art {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    overflow: hidden;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.album-art image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.rotate {
    animation: rotate 10s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.song-info {
    text-align: center;
    margin-bottom: 20px;
}

.song-name {
    font-size: 24px;
    font-weight: bold;
}

.artist-name {
    font-size: 18px;
    color: #ccc;
}

.lyric-scroll {
    width: 80%;
    height: 100px; /* 设置歌词容器的高度 */
    color: #fff;
    font-size: 16px;
    text-align: center;
    line-height: 1.5;
    z-index: 2;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    margin-bottom: 20px; /* 增加歌词和进度条之间的间距 */
}

.progress-container {
    width: 80%;
    position: relative;
    margin-bottom: 20px;
    height: 10px; /* 增加进度条容器的高度 */
    background-color: #f0f0f0; /* 背景颜色 */                 
    border-radius: 5px; /* 圆角 */
    box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1); /* 内阴影 */
}

.progress-bar {
    width: 100%;
    height: 100%;
    border-radius: 5px;
    position: relative;
    overflow: hidden; /* 防止进度条溢出 */
}

.progress {
    height: 100%;
    background-color: #d43c33;
    border-radius: 5px;
    transition: width 0.3s ease; /* 增加过渡效果 */
    box-shadow: 0 0 5px rgba(212, 60, 51, 0.5); /* 外阴影 */
}

.progress-thumb {
    position: absolute;
    top: 50%;
    left: 0;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    background-color: #fff;
    border-radius: 50%;
    cursor: pointer;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.3); /* 外阴影 */
    transition: left 0.3s ease; /* 增加过渡效果 */
}

.control-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
}

.control-buttons .iconfont {
    font-size: 30px;
    margin: 0 20px;
    cursor: pointer;
}

.time-display {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
}

.needle-playing {
    transform: translateX(-50%) rotate(25deg); /* 调整唱针角度 */
}
</style>